package cn.sc.allinpay.allfavour.business.paymentresult;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.allinpay.usdk.core.data.ResponseData;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.pai.common.listener.OnPromptListener;
import cn.pai.common.utils.AmtUtils;
import cn.pai.mvp.callback.MpCallBack;
import cn.pai.mvp.intervenor.Intervenor;
import cn.pai.mvp.presenter.PaiPresenter;
import cn.sc.allinpay.allfavour.app.Constant;
import cn.sc.allinpay.allfavour.business.common.data.OrderData;
import cn.sc.allinpay.allfavour.business.common.data.OrderPaymentInfo;
import cn.sc.allinpay.allfavour.business.common.data.PosData;
import cn.sc.allinpay.allfavour.business.common.data.SpOrderInfo;
import cn.sc.allinpay.allfavour.business.common.data.TransRecord;
import cn.sc.allinpay.allfavour.business.main.MainActivity;
import cn.sc.allinpay.allfavour.module.allin.AllinUtils;
import cn.sc.allinpay.allfavour.module.device.DeviceLogin;
import cn.sc.allinpay.allfavour.module.printer.IPrinter;
import cn.sc.allinpay.allfavour.module.printer.PrintData;
import cn.sc.allinpay.allfavour.module.printer.PrintManager;

/**
 * 去支付 presenter
 * author：pany
 * on 2017/12/1 11:27
 */
public class PaymentResultPresenter extends PaiPresenter<PaymentResultContract.View> implements PaymentResultContract.Presenter {
    public static final int REQ_PRINT_MERCHANT = 0x011;
    public static final int REQ_PRINT_CUSTOMER = 0x022;
    private PaymentResultModel model = new PaymentResultModel();
    private OrderData order;//交易订单对象
    private SpOrderInfo orderInfo;
    private PosData posData;
    private TransRecord transRecord;//交易记录，部分抵扣成功和交易详情进入时
    private IPrinter printer;
    private boolean hasLeave;

    @Override
    protected Intervenor createIntervenor() {
        return new Intervenor() {
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                Bundle bundle = view.getBundle();
                //传过来会对调,我也不知道啥原因
                order = bundle.getParcelable(Constant.BundleKey.PAY_ORDER);
//                String orderCode = order.getSpOrderId();
//                String orderId = order.getSpOrderCode();
//                order.setSpOrderCode(orderCode);
//                order.setSpOrderId(orderId);
                transRecord = bundle.getParcelable(Constant.BundleKey.TRANS_RECORD);
                posData = bundle.getParcelable(Constant.BundleKey.POS_DATA);
                orderInfo = bundle.getParcelable(Constant.BundleKey.SP_ORDER_INFO);
            }

            @Override
            public void onResume() {
                super.onResume();
                DeviceLogin.login(view.getContext());
            }

            @Override
            public void onPause() {
                super.onPause();
                DeviceLogin.logout();
            }

            public void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                if (data != null && data.getExtras() != null) {
                    Bundle extras = data.getExtras();
                    ResponseData result = (ResponseData) extras.getSerializable("RESPONSE");
                    if (result != null) {
                        if (result.getValue("REJCODE").equals("00")) {
                            if (REQ_PRINT_MERCHANT == requestCode) {
                                AllinUtils.printOrder(orderInfo, false,false, view.getActivity(), REQ_PRINT_CUSTOMER);
                            } else if (REQ_PRINT_CUSTOMER == requestCode) {
                                print();
                            }
                        } else {
                            String error = result.getValue("REJCODE");
                            view.toast(error);
                        }
                    }
                }
            }
        };
    }

    @Override
    public void start() {
        if (initData()) {
            initView();
            refreshOrder();
        } else {
            view.finish();
        }
    }

    /**
     * 数据初始化
     *
     * @return
     */
    private boolean initData() {
        if (order == null) {
            if (transRecord == null || TextUtils.isEmpty(transRecord.getOrderData())) {
                view.toast("订单数据为空");
                return false;
            }
            order = JSON.parseObject(transRecord.getOrderData(), OrderData.class);
        }
        return true;
    }

    /**
     * 初始化视图
     */
    private void initView() {
        view.showOrderId(order.getOrderId());
    }

    /**
     * 修改交易记录
     *
     * @param state 支付状态  1:支付中 2:支付成功(全单支付完成) 3:撤销中(尚有其他子订单尚未撤销成功的) 4:撤销成功(全单撤销完成)
     * @return
     */
    private int updRecord(int state) {
        transRecord.setPosData(JSON.toJSONString(posData));
        transRecord.setState(state);
        transRecord.setOrderData(JSON.toJSONString(order));
        return model.updTransRecord(transRecord);
    }

    /**
     * 保存交易记录
     *
     * @param orderId   订单id
     * @param state     支付状态  1:支付中 2:支付成功(全单支付完成) 3:撤销中(尚有其他子订单尚未撤销成功的) 4:撤销成功(全单撤销完成)
     * @param sellState 抵扣状态  0:无抵扣(普通交易) 1:抵扣成功  2:抵扣撤销 3:全额抵扣成功
     * @return
     */
    private int saveRecord(String orderId, int state, int sellState) {
        TransRecord record = new TransRecord();
        record.setTransNo(orderId);//订单id
        record.setOrderId(orderId);//订单id
        record.setTransAmt(order.getTransAmt());//总交易金
        record.setPaidAmt(order.getPaidAmt());//实际支付金额
        record.setDisRightsAmt(order.getMemberData() != null ? order.getMemberData().getOilDiscountAmt().toString() : null);//会员优惠金额
        record.setDisCouponAmt(order.getDisCouponAmt());//卡券使用金额
        record.setDisEWalletAmt(order.getDisEWalletAmt());//电子钱包使用金额

        if (posData.getDateTime() == null) {
            Date myDate1 = new Date();
            DateFormat dateFormat2 = new SimpleDateFormat("yyyyMMddHHmmss");
            posData.setDateTime(dateFormat2.format(myDate1));//交易时间 格式yyyyMMddHHmmss
        }
        record.setTransDate(posData.getDateTime().substring(0, 8));//交易日期
        record.setTransTime(posData.getDateTime().substring(8));//交易时间
        record.setState(state);
        record.setSellState(sellState);//销账成功
        record.setOrderData(JSON.toJSONString(order));
        record.setPosData(JSON.toJSONString(posData));
        transRecord = record;
        return model.saveTransRecord(record);
    }

    /**
     * 打印支付摘要
     */
    public void print() {
        //因为onActivityResult回来没有立即执行onResume方法
        DeviceLogin.login(view.getContext());
        view.loading("交易成功，正在打印...");
        PrintData data = new PrintData();
        data.setMerchantName(model.getGlobal().getConfigData().getMerName());
        data.setTerminalId(model.getGlobal().getConfigData().getTerId());
        data.setOperNo(order.getCashierNo());
        data.setOilName(order.getOilName());
        data.setOperName(order.getCashierName());
        data.setOrderId(order.getOrderId());//订单号
        data.setAmt(order.getTransAmt());//订单总金额
        data.setCardNo(order.getMemberData() != null ? order.getMemberData().getCardNo() : null);//会员卡号
        data.setDisRightsAmt(order.getMemberData() != null ? order.getMemberData().getOilDiscountAmt().toString() : null);//会员权益优惠
        data.setDisCouponAmt(order.getDisCouponAmt());//卡券使用金额
        data.setDisEWalletAmt(order.getDisEWalletAmt());//电子钱包使用金额

        data.setTime(posData.getDateTime());//交易时间
        data.setCashAmt(posData.getCashAmt());//现金交易金额
        data.setTrsAmt(posData.getAmount());//非现金交易金额
        data.setCouponUrl(model.getGlobal().getCashierData().getUrlPrefix());
        printer = PrintManager.createPrinter(PrintManager.PRINT_CASHIER, data);
        printer.print(new IPrinter.OnPrintListener() {
            @Override
            public void onStart(int step) {

            }

            @Override
            public void onSuccess(int step) {
                view.loaded();
                view.toast("打印成功");
                String printCount = order.getPrintCount();
                if (printCount == null) {
                    order.setPrintCount("1");
                } else {
                    printCount = Integer.parseInt(printCount) + 1 + "";
                    order.setPrintCount(printCount);
                }

                transRecord.setOrderData(JSON.toJSONString(order));
                model.updTransRecord(transRecord);
                view.toActivity(MainActivity.class, null);
                view.finish();
                view.showHomeBtn(View.VISIBLE);
            }

            @Override
            public void onFail(int code, String msg) {
                view.loaded();
                view.prompt(false, msg + ",是否继续打印", new OnPromptListener("确定", "取消") {
                    @Override
                    public void onPositive(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        print();
                    }

                    @Override
                    public void onNegative(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        view.toActivity(MainActivity.class, null);
                        view.finish();

                    }
                });
            }
        });
    }

    public void refreshOrder() {
        if (hasLeave) {
            return;
        }
        if (orderInfo.getOrderStatus() == 1) {
            this.checkSpOrderInfo();
            return;
        }
        model.spOrderInfo(order.getOrderId(), new MpCallBack<SpOrderInfo, String>() {
            @Override
            public void onSuccess(SpOrderInfo orderInfo1) {
                //TODO: 更新 POSDATA 中的 transType 及扫码单号
                orderInfo = orderInfo1;
                if (hasLeave) {
                    return;
                }
                checkSpOrderInfo();
            }

            @Override
            public void onFailure(String resp, String message) {
                if (hasLeave) {
                    return;
                }

                if (transRecord != null) {

                    updRecord(1);
                } else {

                    saveRecord(order.getOrderId(), 1, 0);
                }
                view.loaded();
                view.prompt(message);
            }
        });
    }

    public void checkSpOrderInfo() {
        if (orderInfo.getOrderPayment() != null && orderInfo.getOrderPayment().size() != 0) {
            OrderPaymentInfo orderPaymentInfo = orderInfo.getOrderPayment().get(0);
            int paymentFrom = orderPaymentInfo.getPaymentFrom();
            String payFrom = "扫码支付";
            if (paymentFrom == 0) {
                payFrom = "微信支付";
            } else if (paymentFrom == 1) {
                payFrom = "支付宝支付";
            } else if (paymentFrom == 2) {
                payFrom = "手机 QQ 支付";
            } else if (paymentFrom == 3) {
                payFrom = "银联支付";
            }
            posData.setTransType(payFrom);//交易类型
            posData.setBatchNo(orderPaymentInfo.getTrxId());//批次号

            String dateTime = orderInfo.getCreateTime();
            Date myDate1 = new Date();
            DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                myDate1 = dateFormat1.parse(dateTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            DateFormat dateFormat2 = new SimpleDateFormat("yyyyMMddHHmmss");
            posData.setDateTime(dateFormat2.format(myDate1));//交易时间 格式yyyyMMddHHmmss
            String orderStatus = "";
            if (orderInfo.getRmaId() == null || (orderInfo.getRmaId() != null && orderInfo.getRefundStatus() == 3)) {
                if (orderInfo.getOrderStatus() == 0) {
                    orderStatus = "待支付";
                    if (transRecord != null) {

                        updRecord(0);
                    } else {

                        saveRecord(order.getOrderId(), 0, 0);
                    }

                } else if (orderInfo.getOrderStatus() == 1) {
                    view.showHomeBtn(View.GONE);
                    orderStatus = "支付成功";
                    if (transRecord != null) {
                        updRecord(2);
                    } else {

                        saveRecord(order.getOrderId(), 2, 0);
                    }

                    model.payNotify(order.getOrderId(), "scan", "PAY", orderPaymentInfo.getPaymentTime(), AmtUtils.changeY2F(posData.getCashAmt()), AmtUtils.changeY2F(orderPaymentInfo.getPaymentAmount()), null, new MpCallBack<JSONObject, String>() {
                        @Override
                        public void onSuccess(JSONObject resp) {
                            view.loaded();
                            AllinUtils.printOrder(orderInfo, true,false, view.getActivity(), REQ_PRINT_MERCHANT);
                        }
                        @Override
                        public void onFailure(String resp, String message) {
                            view.loaded();
                            view.prompt(message);
                        }
                    });
                } else if (orderInfo.getOrderStatus() == 2) {
                    orderStatus = "待支付";
                    posData = null;
                    if (transRecord != null) {

                        updRecord(0);
                    } else {

                        saveRecord(order.getOrderId(), 0, 0);
                    }

                } else if (orderInfo.getOrderStatus() == 3) {
                    orderStatus = "已撤销";

                    if (transRecord != null) {

                        updRecord(4);
                    } else {

                        saveRecord(order.getOrderId(), 4, 0);
                    }

                } else if (orderInfo.getOrderStatus() == 4) {
                    orderStatus = "处理中";
                    if (transRecord != null) {

                        updRecord(1);
                    } else {

                        saveRecord(order.getOrderId(), 1, 0);
                    }

                    refreshOrder();
                }
            } else if (orderInfo.getRmaId() != null && orderInfo.getRefundStatus() != 3) {
                if (orderInfo.getRefundStatus() == 1) {
                    orderStatus = "退款中";
                    if (transRecord != null) {

                        updRecord(3);
                    } else {

                        saveRecord(order.getOrderId(), 3, 0);
                    }

                } else if (orderInfo.getRefundStatus() == 2) {
                    orderStatus = "退款成功";
                    if (transRecord != null) {

                        updRecord(4);
                    } else {

                        saveRecord(order.getOrderId(), 4, 0);
                    }

                }
            }
            view.showOrderStatus(orderStatus);
        } else {
            view.showOrderStatus("待支付");
            if (transRecord != null) {
                posData = null;
            }

        }
    }

    @Override
    public void goHme() {
        hasLeave = true;
        view.toActivity(MainActivity.class, null);
        view.finish();
    }
}
